﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using WmWebSystem.Models;
using WmWebSystem.Service;
using WmWebSystem.DbHelper;
using System.IO;

namespace WmWebSystem.Controllers
{
    public class AccountController : Controller
    {
        WmDb mydb = new WmDb();
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            var model = NewsHelper.FindOneNewsby(4);
            if (model != null)
            {
                ViewBag.Clause = model.Content.Replace("<br/>", "");
            }
            else 
            {
                ViewBag.Clause = "";
            }
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                string logo="~\\Content\\UserAccount\\wm.png";
                string telephone = "";

                if (UserAccountHelper.IsExistUserName(model.UserName))
                {
                    ModelState.AddModelError("", "该用户名已存在，请填写新的用户名！");
                }
                else
                {
                    Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
                    if (createStatus == MembershipCreateStatus.Success)
                    {

                        UserAccountHelper.AddNewAccountToCustomers(model.UserName, model.Email, telephone, logo);

                        FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(createStatus));
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "当前密码不正确或新密码无效.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }


        [Authorize]
        public ActionResult AccountInf()
        {
            string name = HttpContext.User.Identity.Name;
            var account = UserAccountHelper.FindAccountByName(name);
            ViewBag.Logo = account.Logo;
            return View(account);
        }
        [Authorize]
        public ActionResult ChangeAccountInf() 
        {
            string name = HttpContext.User.Identity.Name;
            var account = UserAccountHelper.FindAccountByName(name);
            return View(account);
        }
        [Authorize]
        [HttpPost]
        public ActionResult ChangeAccountInf(UserAccount model)
        {

            try
            {
                var customer = mydb.UserAccounts.Find(model.UserId);

                string path = null;
                string logo = null;
                string fileOldName = "";
                string extension = "";


                foreach (string image in Request.Files)
                {
                    if (!WmWebSystem.Service.HasFiles.HasFile(Request.Files[image]))
                        continue;

                    string createPath = AppDomain.CurrentDomain.BaseDirectory + @"Content\UserAccount\"+customer.Name;
                    path = HasFolders.HasFolder(createPath);

                    //获得文件扩展名
                    fileOldName = Path.GetFileName(Request.Files[image].FileName);
                    extension = Path.GetExtension(fileOldName);//扩展名 ".xxx"

                    string miniType = Request.Files[image].ContentType.ToLower();

                    Stream fileStream = Request.Files[image].InputStream;

                    //文件重命名
                    string fileNewName = RandomNumberTo.RandomNumberToName() + extension;

                    Request.Files[image].SaveAs(Path.Combine(path, fileNewName));
                    path = path + "\\" + fileNewName;
                    logo = "~\\Content\\Sliders\\" + fileNewName;

                }
                if (logo != null || logo != "")
                {
                    customer.Logo = logo;
                }
                UpdateModel(customer);
                mydb.SaveChanges();
                return RedirectToAction("AccountInf","Zone");
            }
            catch (Exception e)
            {
                string error = "修改失败，请查看详细错误信息:" + e;
                return RedirectToAction("Error", "Notice", new { message = error });
            }
        }


        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "该用户名已被使用. 请尝试其他用户名.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "当前邮箱已经被使用.请使用其它邮箱.";

                case MembershipCreateStatus.InvalidPassword:
                    return "您提供的密码无效. 请重新输入有效的密码.";

                case MembershipCreateStatus.InvalidEmail:
                    return "您提供的邮箱无效. 请重新输入有效的邮箱.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "您提供的密码答案是无效的,请检查后再试一次.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "您提供的问题是无效的,请检查后再试一次.";

                case MembershipCreateStatus.InvalidUserName:
                    return "您提供的用户名是无效的,请检查后再试一次.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
